package avicit.bdp.dds.server.master.processor;

import avicit.bdp.common.utils.SpringApplicationContext;
import avicit.bdp.common.utils.redis.RedisCacheHelper;
import avicit.bdp.dds.dispatch.enums.ExecutionStatus;
import avicit.bdp.core.util.json.JSONUtils;
import avicit.bdp.dds.common.thread.Stopper;
import avicit.bdp.dds.common.thread.ThreadUtils;
import avicit.bdp.dds.common.utils.Preconditions;
import avicit.bdp.dds.dao.entity.ProcessInstance;
import avicit.bdp.dds.dao.entity.TaskInstance;
import avicit.bdp.dds.remote.command.Command;
import avicit.bdp.dds.remote.command.CommandType;
import avicit.bdp.dds.remote.command.TaskExecuteResponseCommand;
import avicit.bdp.dds.remote.processor.NettyRequestProcessor;
import avicit.bdp.dds.remote.utils.FastJsonSerializer;
import avicit.bdp.dds.server.master.cache.TaskInstanceCacheManager;
import avicit.bdp.dds.server.master.cache.impl.TaskInstanceCacheManagerImpl;
import avicit.bdp.dds.server.master.processor.queue.TaskResponseEvent;
import avicit.bdp.dds.server.master.processor.queue.TaskResponseService;
import avicit.bdp.dds.service.process.ProcessService;
import io.netty.channel.Channel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static avicit.bdp.dds.common.Constants.SLEEP_TIME_MILLIS;

/**
 * task response processor
 */
public class TaskResponseProcessor implements NettyRequestProcessor {

    private final Logger logger = LoggerFactory.getLogger(TaskResponseProcessor.class);

    /**
     * process service
     */
    private final TaskResponseService taskResponseService;

    /**
     * taskInstance cache manager
     */
    private final TaskInstanceCacheManager taskInstanceCacheManager;

    /**
     * processService
     */
    private ProcessService processService;

    public TaskResponseProcessor() {
        this.taskResponseService = SpringApplicationContext.getBean(TaskResponseService.class);
        this.taskInstanceCacheManager = SpringApplicationContext.getBean(TaskInstanceCacheManagerImpl.class);
        this.processService = SpringApplicationContext.getBean(ProcessService.class);
    }

    /**
     * task final result response
     * need master process , state persistence
     *
     * @param channel channel
     * @param command command
     */
    @Override
    public void process(Channel channel, Command command) {
        Preconditions.checkArgument(CommandType.TASK_EXECUTE_RESPONSE == command.getType(),
                String.format("invalid command type : %s", command.getType()));

        TaskExecuteResponseCommand responseCommand = FastJsonSerializer.deserialize(command.getBody(),
                TaskExecuteResponseCommand.class);
        logger.info("received command : {}", responseCommand);

        //如果sparkFlow
        String taskStr = RedisCacheHelper.getInstance().get("bdp:dds:task:" + responseCommand.getTaskInstanceId());
        //缓存信息是sparkFlow的虚拟节点
        if (StringUtils.isNotBlank(taskStr)) {
            TaskInstance taskInstance = JSONUtils.parseObject(taskStr, TaskInstance.class);
            ProcessInstance instance = new ProcessInstance();
            instance.setState(responseCommand.getStatus());
            instance.setEndTime(responseCommand.getEndTime());
            instance.setId(taskInstance.getProcessInstanceId());
            processService.updateProcessInstanceByPrimaryKeySelective(instance);
            return;
        }

        taskInstanceCacheManager.cacheTaskInstance(responseCommand);

        ExecutionStatus responseStatus = ExecutionStatus.of(responseCommand.getStatus());

        // TaskResponseEvent
        TaskResponseEvent taskResponseEvent = TaskResponseEvent.newResult(
                responseCommand.getStatus(),
                responseCommand.getEndTime(),
                responseCommand.getProcessId(),
                responseCommand.getAppIds(),
                responseCommand.getTaskInstanceId());

        taskResponseService.addResponse(taskResponseEvent);

        while (Stopper.isRunning()) {
            TaskInstance taskInstance = processService.findTaskInstanceById(taskResponseEvent.getTaskInstanceId());

            if (taskInstance != null && responseStatus.typeIsFinished()) {
                break;
            }
            ThreadUtils.sleep(SLEEP_TIME_MILLIS);
        }
    }


}
